package com.example.victory.service;

import com.example.victory.entity.companyEntity.BusChanceEntity;
import com.example.victory.mapper.CustomerMapper;
import com.example.victory.swagger.handler.MiniAppChanceApiDelegate;
import com.example.victory.swagger.model.*;
import com.example.victory.utils.AnalysisUtils;
import com.example.victory.utils.CrmUtils;
import com.cgws.fintech.sdk.api.inner.security.model.User;
import com.cgws.fintech.sdk.api.mvp.model.ApiRequestCustomerQueryData;
import com.cgws.fintech.sdk.api.mvp.model.CustomerAccount;
import com.cgws.fintech.sdk.common.utils.MoneyHelper;
import com.example.victory.common.web.ServiceHelper;
import com.cgws.fintech.sdk.inner.utils.web.SessionService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class MiniAppBusChanceService implements MiniAppChanceApiDelegate {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private MvpLoginService mvpLoginService;
    @Autowired
    private SessionService sessionService;

    @Override
    public ResponseEntity<ApiResponseBusChance> getCustBusChance(ApiRequestBusChance param) {

        ApiRequestBusChanceData data = param.getData();
        ServiceHelper.checkDataNotNull(data, "data");
        ApiRequestBusChanceData.BusTypeEnum busType = data.getBusType();
        ServiceHelper.checkDataNotNull(busType, "data.busType");
        Boolean isOpen = data.isIsOpen();
        ServiceHelper.checkDataNotNull(isOpen, "data.isOpen");

        ApiResponseBusChanceData apiResponseBusChanceData = new ApiResponseBusChanceData();

        // 获取当前用户
        User user = sessionService.getCurrentUserSession(true).getUser();
        String crmId = user.getCrmId();
        if (crmId == null) crmId = "";
//        if (crmId == null) crmId = "1000581";
        List<BusChanceEntity> entities = customerMapper.getBusChanceInfoPage(crmId, data);

        List<BusChanceCustInfo> custInfoList = new ArrayList<>();
        List<ApiRequestCustomerQueryData> customerQueryDataList = Lists.newArrayList();
        if (entities == null || entities.size() == 0) {
            apiResponseBusChanceData.setItems(Collections.emptyList());
            return ResponseEntity.ok(new ApiResponseBusChance().data(apiResponseBusChanceData));
        }

        entities.forEach( entity -> {
            ApiRequestCustomerQueryData customerQueryData=new ApiRequestCustomerQueryData();
            customerQueryData.setCustNum(entity.getCustomerId());
            customerQueryDataList.add(customerQueryData);

            BusChanceCustInfo chanceCustInfo = new BusChanceCustInfo();
            chanceCustInfo.setName(entity.getName());
            chanceCustInfo.setCustomerId(entity.getCustomerId());
            chanceCustInfo.setPhone(entity.getPhone());
            chanceCustInfo.setRelationType(AnalysisUtils.getRelationType(entity.getRelationType()));
            if (entity.getRiskLevel() != null) chanceCustInfo.setRiskLevel(entity.getRiskLevel());
            if (entity.getCustLevel() != null) chanceCustInfo.setCustLevel(entity.getCustLevel());
            chanceCustInfo.setIsService(entity.getIsService() > 0);

            ArrayList<KeyValueDetail> keyValueList = Lists.newArrayList();
            KeyValueDetail total = new KeyValueDetail();
            total.setName("总资产");
            total.setValue(MoneyHelper.formatMoney(new BigDecimal(entity.getTotal().trim())));
            keyValueList.add(total);

            KeyValueDetail turnoverRate = new KeyValueDetail();
            turnoverRate.setName("周转率");
            turnoverRate.setValue(entity.getTurnoverRate().trim().equals("0.00")?"0":entity.getTurnoverRate().trim());
            keyValueList.add(turnoverRate);

            KeyValueDetail totalMarket = new KeyValueDetail();
            totalMarket.setName("总市值");
            totalMarket.setValue(MoneyHelper.formatMoney(new BigDecimal(entity.getTotalMarket().trim())));
            keyValueList.add(totalMarket);

            KeyValueDetail commission = new KeyValueDetail();
            commission.setName("佣金");
            commission.setValue(MoneyHelper.formatMoney(new BigDecimal(entity.getCommission().trim())) +
                    (entity.getCommissionRate().trim().equals("0.00")?"(0‰)":"(" + entity.getCommissionRate().trim()+"‰)"));
            keyValueList.add(commission);

            KeyValueDetail availableTotal = new KeyValueDetail();
            availableTotal.setName("可用资产");
            availableTotal.setValue(MoneyHelper.formatMoney(new BigDecimal(entity.getAvailableTotal().trim())));
            keyValueList.add(availableTotal);

            KeyValueDetail openDate = new KeyValueDetail();
            openDate.setName("开户日期");
            openDate.setValue(entity.getOpenDate().trim());
            keyValueList.add(openDate);

            chanceCustInfo.setDetails(keyValueList);
            custInfoList.add(chanceCustInfo);
        });
        if(customerQueryDataList.size()>0){
            List<CustomerAccount> customerAccountList = CrmUtils.getCustAccountListByIds(mvpLoginService, customerQueryDataList);
            if (customerAccountList != null) {
                custInfoList.forEach(customer -> {
                    customerAccountList.forEach(customerAccount->{
                        if(!StringUtils.isEmpty(customerAccount.getFcid())&&customer.getCustomerId().equals(customerAccount.getCustNum())){
                            customer.setImId(customerAccount.getFcid());
                        }
                    });
                });
            }
        }
        return ResponseEntity.ok(new ApiResponseBusChance().data(apiResponseBusChanceData.items(custInfoList)));
    }
}
